package com.jingzhi.huimiao;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.StrictMode;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.jingzhi.huimiao.bean.RoleInfo;
import com.jingzhi.huimiao.bean.WordInfo;
import com.jingzhi.huimiao.bean.RoleInfo.RightInfo;
import com.jingzhi.huimiao.bean.RoleInfo.WordId;
import com.jingzhi.huimiao.utils.CanstantUtils;
import com.jingzhi.huimiao.utils.DataStoreUtil;
import com.jingzhi.huimiao.utils.HttpUtils;
import com.jingzhi.huimiao.utils.SQLdm;

public class ChooseRoleActivity extends Activity implements OnClickListener {

	protected static final int WHAT = 0;
	private Button btn_to_main;
	private ViewPager vp_role;
	private int ids[];
	private ImageView iv_next;
	private ImageView iv_enter;
	private ImageView iv_last;
	private int itempisition;

	public static String rolenum;
	public static String wordId;
	private int uid;

	private Handler handler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case WHAT:
				startActivity(new Intent(ChooseRoleActivity.this,
						MainActivity.class));

				if (db != null) {
					db.close();
				}
				finish();
				break;

			default:
				break;
			}
		};
	};
	private SQLiteDatabase db;
	private Cursor rolecur;
	private Cursor rawQuery;
	private long word_id;
	private Cursor rightcur;
	private RightInfo[] rightinfo;
	private String responseData;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);// 去掉标题栏，一定要在setContentView之前
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_choose_role);

		// 打开数据库输出流
		SQLdm s = new SQLdm();
		db = s.openDatabase(getApplicationContext());

		btn_to_main = (Button) findViewById(R.id.btn_to_main);
		vp_role = (ViewPager) findViewById(R.id.vp_role);
		iv_next = (ImageView) findViewById(R.id.iv_next);
		iv_enter = (ImageView) findViewById(R.id.iv_enter);
		iv_last = (ImageView) findViewById(R.id.iv_last);

		ids = new int[] { R.drawable.role_1_03, R.drawable.role_2_03,
				R.drawable.role_3_03 };
		btn_to_main.setOnClickListener(this);
		addListener();

		vp_role.setAdapter(new RoleAdapter());
		vp_role.setOnPageChangeListener(new OnPageChangeListener() {

			@Override
			public void onPageSelected(int position) {
				// addListener();
			}

			@Override
			public void onPageScrolled(int position, float positionOffset,
					int positionOffsetPixels) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onPageScrollStateChanged(int state) {
				// TODO Auto-generated method stub

			}
		});

	}

	class RoleAdapter extends PagerAdapter {

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return 3;
		}

		@Override
		public boolean isViewFromObject(View view, Object object) {
			// TODO Auto-generated method stub
			return view == object;
		}

		@Override
		public Object instantiateItem(ViewGroup container, int position) {
			View view = View.inflate(getApplicationContext(),
					R.layout.guide_vp_item, null);
			ImageView role = (ImageView) view.findViewById(R.id.imageView);
			role.setBackgroundResource(ids[position]);
			container.addView(view);
			return view;
		}

		@Override
		public void destroyItem(ViewGroup container, int position, Object object) {
			// TODO Auto-generated method stub
			// super.destroyItem(container, position, object);
			container.removeView((View) object);
		}

	}

	private void addListener() {
		iv_next.setOnClickListener(this);
		iv_enter.setOnClickListener(this);
		iv_last.setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {

		switch (v.getId()) {
		case R.id.btn_to_main:
			// vp_role.setCurrentItem(item);
			break;
		case R.id.iv_next:
			itempisition = vp_role.getCurrentItem();
			if (itempisition != 2) {
				vp_role.setCurrentItem(++itempisition);
			}
			break;
		case R.id.iv_enter:

			// 用于捕获磁盘访问或者网络访问中与主进程之间交互产生的问题
			StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
					.detectDiskReads().detectDiskWrites().detectNetwork()
					.penaltyLog().build());
			StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
					.detectLeakedSqlLiteObjects().detectLeakedClosableObjects()
					.penaltyLog().penaltyDeath().build());

			// new Thread(){

			try {
				// 创建用户信息类
				RoleInfo roleinfo = new RoleInfo();

				// 将用户信息存放在Map中
				Map<String, String> roleInfo = new HashMap<String, String>();
				// roleInfo.put("role", vp_role.getCurrentItem() + 1 + "");
				roleinfo.role = (long) (vp_role.getCurrentItem() + 1);

				DataStoreUtil.putint(ChooseRoleActivity.this, "ChooseRole",
						(long) (vp_role.getCurrentItem() + 1));

				Long uid = DataStoreUtil.getLong(ChooseRoleActivity.this,
						"userid");
				// roleInfo.put("uid", uid + "");
				roleinfo.uid = uid;

				JSONObject ClientKey = new JSONObject();

				ClientKey.put("role", roleinfo.role);

				ClientKey.put("uid", roleinfo.uid);

				// 根据选择的角色去对应role表和right表查询进度
				if ((vp_role.getCurrentItem() + 1) == 1) {
					// 查询单词进度
					rawQuery = db.rawQuery("select * from role1 where user_id="
							+ uid + ";", null);
					if (rawQuery.moveToFirst()) {
						word_id = rawQuery.getLong(rawQuery
								.getColumnIndex("word_id"));
					}

					ClientKey.put("word", word_id);

					// 查询正确率表
					rightcur = db.rawQuery(
							"select * from right1 where user_id=" + uid + ";",
							null);

					// 创建一个争取率的jsonarray
					JSONArray RightKey = new JSONArray();

					while (rightcur.moveToNext()) {

						JSONObject RightInfo = new JSONObject();

						//
						long userId = rightcur.getLong(rightcur
								.getColumnIndex("user_id"));
						long taskId = rightcur.getLong(rightcur
								.getColumnIndex("task_id"));
						float rightLv = rightcur.getFloat(rightcur
								.getColumnIndex("right_lv"));
						Log.e("HEHE", "-----" + taskId + "-----" + rightLv);

						//
						RightInfo.put("userId", userId);
						RightInfo.put("taskId", taskId);
						RightInfo.put("rightLv", rightLv);

						RightKey.put(RightInfo);
					}

					ClientKey.put("right", RightKey);

				} else if ((vp_role.getCurrentItem() + 1) == 2) {
					// 查询单词进度
					rawQuery = db.rawQuery("select * from role2 where user_id="
							+ uid + ";", null);
					if (rawQuery.moveToFirst()) {
						word_id = rawQuery.getLong(rawQuery
								.getColumnIndex("word_id"));
					}

					ClientKey.put("word", word_id);

					// 查询正确率表
					rightcur = db.rawQuery(
							"select * from right2 where user_id=" + uid + ";",
							null);

					// 创建一个争取率的jsonarray
					JSONArray RightKey = new JSONArray();

					while (rightcur.moveToNext()) {

						JSONObject RightInfo = new JSONObject();

						//
						long userId = rightcur.getLong(rightcur
								.getColumnIndex("user_id"));
						long taskId = rightcur.getLong(rightcur
								.getColumnIndex("task_id"));
						float rightLv = rightcur.getFloat(rightcur
								.getColumnIndex("right_lv"));
						Log.e("HEHE", "-----" + taskId + "-----" + rightLv);

						//
						RightInfo.put("userId", userId);
						RightInfo.put("taskId", taskId);
						RightInfo.put("rightLv", rightLv);

						RightKey.put(RightInfo);
					}

					ClientKey.put("right", RightKey);
				} else {
					// 查询单词进度
					rawQuery = db.rawQuery("select * from role3 where user_id="
							+ uid + ";", null);
					if (rawQuery.moveToFirst()) {
						word_id = rawQuery.getLong(rawQuery
								.getColumnIndex("word_id"));
					}

					ClientKey.put("word", word_id);

					// 查询正确率表
					rightcur = db.rawQuery(
							"select * from right3 where user_id=" + uid + ";",
							null);

					// 创建一个争取率的jsonarray
					JSONArray RightKey = new JSONArray();

					while (rightcur.moveToNext()) {

						JSONObject RightInfo = new JSONObject();

						//
						long userId = rightcur.getLong(rightcur
								.getColumnIndex("user_id"));
						long taskId = rightcur.getLong(rightcur
								.getColumnIndex("task_id"));
						float rightLv = rightcur.getFloat(rightcur
								.getColumnIndex("right_lv"));
						Log.e("HEHE", "-----" + taskId + "-----" + rightLv);

						//
						RightInfo.put("userId", userId);
						RightInfo.put("taskId", taskId);
						RightInfo.put("rightLv", rightLv);

						RightKey.put(RightInfo);
					}

					ClientKey.put("right", RightKey);
				}

				if (rightcur != null && !rightcur.isClosed()) {
					rightcur.close();
				}

				// 将对象转化成json格式
				// String json = new Gson ().toJson(roleinfo);

				/* 封装Person对象 */

				JSONObject params = new JSONObject();

				params.put("Person", ClientKey);

				// 传输json数据
				/* 把JSON数据转换成String类型使用输出流向服务器写 */

				String content = String.valueOf(params);
				Log.e("CONTENT", content);

				URL url = new URL(CanstantUtils.choose_url);
				HttpURLConnection conn = (HttpURLConnection) url
						.openConnection();

				conn.setConnectTimeout(5000);

				conn.setDoOutput(true);// 设置允许输出

				conn.setRequestMethod("POST");

				conn.setRequestProperty("User-Agent", "Fiddler");

				conn.setRequestProperty("Content-Type", "application/json");

				// conn.setRequestProperty("Charset", utf-8);

				OutputStream os = conn.getOutputStream();

				os.write(content.getBytes());

				os.close();

				/* 服务器返回的响应码 */

				int code = conn.getResponseCode();

				if (code == 200)

				{

					BufferedReader in = new BufferedReader(
							new InputStreamReader(conn.getInputStream(),
									"UTF-8"));

					String retData = null;

					responseData = "";

					while ((retData = in.readLine()) != null)

					{

						responseData += retData;

					}

					Log.e("RESPONSEDATA", responseData);

					in.close();

					finish();

				}

				else

				{

					Toast.makeText(getApplicationContext(), "数据提交失败",
							Toast.LENGTH_SHORT).show();

				}

				// 对接收到的服务器端的数据进行解析
				// String retStr = HttpUtils.sendPostRequest(
				// CanstantUtils.choose_url, roleInfo, "utf-8");
				// Log.e("TAG------", retStr);
				String retStr = responseData;
				Gson gson = new Gson();
				RoleInfo result = gson.fromJson(retStr, RoleInfo.class);
				RightInfo[] rightinfo = result.right;

				if (rawQuery != null) {
					rawQuery.close();
				}
				// 获取单词进度
				WordId wordId = result.wordId;
				long wid = wordId.getWordId();

				ContentValues values = new ContentValues();
				// Log.e("rightinfo.getindex(i)", rightinfo.length+"");
				if ("role1".equals(result.getFan().toString())) {

					// 对角色表进行查询，如果为空，插入，否则，更新
					rolecur = db.rawQuery("select * from role1 where user_id ="
							+ uid + "", null);
					if (rolecur.getCount() == 0) {
						db.execSQL("insert into role1 (user_id,word_id) values ("
								+ uid + "," + wid + ");");
					} else {
						db.execSQL("update role1 set word_id=" + wid
								+ " where user_id=" + uid + ";");
					}

					DataStoreUtil.putint(ChooseRoleActivity.this, "roleid",
							(long) 1);
					//
//					db.execSQL("update user set role_id=1  where id='" + uid
//							+ "';");

					// 删除right表中所有数据'
					db.execSQL("delete from right1 where user_id=" + uid + ";");

					for (int i = 0; i < rightinfo.length; i++) {
						values.put("right_lv", rightinfo[i].rightLv);
						values.put("task_id", rightinfo[i].taskId);
						values.put("user_id", rightinfo[i].userId);

						// 将正确率插入到表中
						db.insert("right1", null, values);
					}
					//
					// rolenum = "role1";
				} else if ("role2".equals(result.getFan().toString())) {

					// 对角色表进行查询，如果为空，插入，否则，更新
					rolecur = db.rawQuery("select * from role2 where user_id ="
							+ uid + "", null);
					if (rolecur.getCount() == 0) {
						db.execSQL("insert into role2 (user_id,word_id) values ("
								+ uid + "," + wid + ");");
					} else {
						db.execSQL("update role2 set word_id=" + wid
								+ " where user_id=" + uid + ";");
					}

					// 删除right表中所有数据'
					db.execSQL("delete from right2 where user_id=" + uid + ";");

					for (int i = 0; i < rightinfo.length; i++) {
						values.put("right_lv", rightinfo[i].rightLv);
						values.put("task_id", rightinfo[i].taskId);
						values.put("user_id", rightinfo[i].userId);

						// 将正确率插入到表中
						db.insert("right2", null, values);
					}

					DataStoreUtil.putint(ChooseRoleActivity.this, "roleid",
							(long) 2);
					//
//					db.execSQL("update user set role_id=2  where id='" + uid
//							+ "';");
					// rolenum = "role2";
				} else if ("role3".equals(result.getFan().toString())) {

					// 对角色表进行查询，如果为空，插入，否则，更新
					rolecur = db.rawQuery("select * from role3 where user_id ="
							+ uid + "", null);
					if (rolecur.getCount() == 0) {
						db.execSQL("insert into role3 (user_id,word_id) values ("
								+ uid + "," + wid + ");");
					} else {
						db.execSQL("update role3 set word_id=" + wid
								+ " where user_id=" + uid + ";");
					}

					// 删除right表中所有数据'
					db.execSQL("delete from right3 where user_id=" + uid + ";");

					for (int i = 0; i < rightinfo.length; i++) {
						values.put("right_lv", rightinfo[i].rightLv);
						values.put("task_id", rightinfo[i].taskId);
						values.put("user_id", rightinfo[i].userId);

						// 将正确率插入到表中
						db.insert("right3", null, values);
					}

					DataStoreUtil.putint(ChooseRoleActivity.this, "roleid",
							(long) 3);

					//
//					db.execSQL("update user set role_id=3  where id='" + uid
//							+ "';");
					// rolenum = "role3";
				}
				handler.sendEmptyMessage(WHAT);

				long hehe = DataStoreUtil.getLong(ChooseRoleActivity.this,
						"roleid");

			} catch (Exception e) {
				e.printStackTrace();
			} finally {

				if (rolecur != null && !rolecur.isClosed()) {
					rolecur.close();
				}

			}

			// break;
		case R.id.iv_last:
			itempisition = vp_role.getCurrentItem();
			if (itempisition != 0) {
				vp_role.setCurrentItem(--itempisition);
			}
			break;

		default:
			break;
		}

	}
}
